package com.tangx.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.tangx.model.common.dtos.ResponseResult;
import com.tangx.model.search.dtos.UserSearchDto;
import com.tangx.search.service.ApUserSearchService;
import com.tangx.search.service.ArticleSearchService;
import com.tangx.utils.common.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ArticleSearchServiceImpl implements ArticleSearchService {


    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private ApUserSearchService apUserSearchService;

    @Override
    public ResponseResult search(UserSearchDto dto) throws IOException {
        Integer userId = ThreadLocalUtil.getUserId();
        if(userId!=null){
            apUserSearchService.insert(dto.getSearchWords(),userId);
        }

        //定义组合搜索条件构建器
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        //添加第一个搜索条件：根据关键词多域搜索
        boolQueryBuilder.must(QueryBuilders.queryStringQuery(dto.getSearchWords()).field("title").field("content").defaultOperator(Operator.OR));
        //添加第二个搜索条件：小于最小发布时间
        boolQueryBuilder.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(boolQueryBuilder); //添加组合搜索条件

        if(dto.getPageNum()<=0){
            dto.setPageNum(1);
        }
        if(dto.getPageSize()>5){
            dto.setPageSize(5);
        }

        //设置分页
        searchSourceBuilder.from((dto.getPageNum()-1)*dto.getPageSize());//从第几条查
        searchSourceBuilder.size(dto.getPageSize()); //查询多少条

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        highlightBuilder.preTags("<font style='color:red; font-size:inherit; '>");
        highlightBuilder.postTags("</font>");
        searchSourceBuilder.highlighter(highlightBuilder); //设置高亮

        SearchRequest searchRequest = new SearchRequest("app_info_article");
        searchRequest.source(searchSourceBuilder);

        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        SearchHit[] searchHits = searchResponse.getHits().getHits();

        //根据搜索命中结果处理响应数据
        List<Map> mapList = new ArrayList<>();
        if(searchHits!=null && searchHits.length>0){
            for (SearchHit searchHit : searchHits) {
                //搜索命中结果里文章的JSON字符串
                String apArticleJson = searchHit.getSourceAsString();
                Map articleMap = JSON.parseObject(apArticleJson,Map.class);

                Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
                if(highlightFields!=null && highlightFields.size()>0){
                    Text[] titles = highlightFields.get("title").fragments();
                    String highlightTitle = StringUtils.join(titles); //带高亮标签的标题
                    if(StringUtils.isNotEmpty(highlightTitle)){
                        articleMap.put("h_title", highlightTitle);
                    }
                } else {
                    articleMap.put("h_title",articleMap.get("title"));//不带高亮标签的标题
                }

                mapList.add(articleMap);
            }
        }


        return ResponseResult.okResult(mapList);
    }
}
